package com.xian.im.web.modules.user;

import com.xian.im.common.model.dto.OrganizationDto;
import com.xian.im.common.result.RestResult;
import com.xian.im.common.result.RestResultBuilder;
import com.xian.im.modules.im.controller.model.login.OrgLoginReq;
import com.xian.im.modules.im.core.IOrganizationCoreService;
import com.xian.im.modules.im.core.LoginService;
import com.xian.im.modules.security.TokenProvider;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author xlr
 * @email 
 * @date 2021-01-18 19:11:56
 */
@RestController
@RequestMapping("im/auth")
@Api(value = "登陆操作", tags = {"登陆"})
public class LoginController {

    @Autowired
    private TokenProvider tokenProvider;
    @Autowired
    private IOrganizationCoreService organizationCoreService;
    @Autowired
    private LoginService loginService;

    @ApiOperation(value = "机构登录", notes = "机构登录")
    @RequestMapping(value = "/org/login",method = RequestMethod.POST)
    public RestResult orgLogin(@RequestBody OrgLoginReq loginReq){

        if (loginService.login(loginReq)){
            OrganizationDto entity = organizationCoreService.findByAK(loginReq.getAccessKey());
            String token = tokenProvider.createOrgToken(entity);
            return RestResultBuilder.builder().success().data(token).build();
        }
        return RestResultBuilder.builder().failure().message("登录错误").build();
    }
    @ApiOperation(value = "机构退出登录", notes = "退出登录")
    @RequestMapping(value = "/logout",method = RequestMethod.POST)
    public RestResult loginOut(@RequestBody OrgLoginReq loginReq){

        if (loginService.login(loginReq)){
            OrganizationDto entity = organizationCoreService.findByAK(loginReq.getAccessKey());
            String token = tokenProvider.createOrgToken(entity);
            return RestResultBuilder.builder().success().data(token).build();
        }
        return RestResultBuilder.builder().failure().message("登录错误").build();
    }

}
